#include "LoginQDialog.h"
#include "ui_LoginQDialog.h"
#include "SqliteDialog.h"


LoginQDialog::LoginQDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginQDialog)
{
    ui->setupUi(this);
    //点击ok按钮发送accepted
    connect (ui->m_btnBox, SIGNAL(accepted()),
            this, SLOT(onAccepted()));
    //点击cancle按钮发送rejected
    connect (ui->m_btnBox, SIGNAL(rejected()),
            this, SLOT(onRejected()));
    //创建数据库
    createDB();
    //创建数据表
    createTable();
}

LoginQDialog::~LoginQDialog()
{
    delete ui;
}

//创建数据库
void LoginQDialog::createDB (void)
{
    //创建数据库
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("login.db");

    //打开数据库
    if (false == db.open ()) {
        qDebug() << db.lastError().text();
    }
}

//创建学生成绩数据表
void LoginQDialog::createTable (void)
{
    QSqlQuery query;
    QString str = QString ("CREATE TABLE login"
             "(root TEXT PRIMARY KEY NOT NULL,"
             "password TEXT NOT NULL)"
             );
    qDebug() << str;
    //执行sql语句
    query.exec (str);
}
void LoginQDialog::queryTable (void)
{
    QString str = QString ("SELECT * FROM student");
    //执行str, 保存结果到model中
    model.setQuery(str);
    //显示model

}
void LoginQDialog::onAccepted (void)
{
    QSqlQuery query;
    query.exec("select * from login");
    for(int i = 0 ; query.seek(i) ; i++){

    //获取当前行的记录
    QSqlRecord record = query.record();
    //获取字段中记录的值
    QString root = record.value("root").toString();
    QString password= record.value("password").toString();
    if(root == ui->m_editUserName->text() && password == ui->m_editPassword->text()){
          flag = 1;
          qDebug ("登录成功");
          qDebug ("进入主界面...");
          close ();
          SqliteDialog new_w;
          new_w.show();
          new_w.exec();
        }

    }
    if(flag == 0){
        QMessageBox msgBox(QMessageBox::Critical,
            windowTitle(), "用户名或密码错误",
            QMessageBox::Ok,
            this
            );
        //显示提示框, 并进入事件循环, 点击消息框按钮会自动退出
        msgBox.exec ();

    }
}
void LoginQDialog::onRejected (void)
{
    //qDebug() << "cancel";
    QMessageBox msgBox(QMessageBox::Question,
            windowTitle(), "确定要退出?",
            QMessageBox::Yes|QMessageBox::No,
            this
            );
    if (msgBox.exec() == QMessageBox::Yes) {
        close ();
    }
}

void LoginQDialog::on_zhuce_clicked()
{
    QSqlQuery query;
    QString root = ui->m_editUserName->text();
    QString password =ui-> m_editPassword->text();
    QString str = QString("INSERT INTO login VALUES('%1', '%2')"
                          ).arg(root).arg(password);

    query.exec(str);
    qDebug("注册成功");
}
